package com.anyikang.volunteer.sos.volunteer.app.main;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.Toast;

import com.anyikang.volunteer.sos.volunteer.R;
import com.anyikang.volunteer.sos.volunteer.app.MyApplication;
import com.anyikang.volunteer.sos.volunteer.app.userInfo.LoginActivity;
import com.anyikang.volunteer.sos.volunteer.utils.Utils;
import com.baidu.navisdk.adapter.BNCommonSettingParam;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;

import java.io.File;


/**
 * 开屏页
 */
public class SplashActivity extends AppCompatActivity {

    private static final int sleepTime = 5000;
    ImageView ivSplash;
    private Activity mActivity;
    private String mSDCardPath = null;
    private static final String APP_FOLDER_NAME = "BNSDKVolunteer";
    private static final String[] authBaseArr = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION};
    private static final int authBaseRequestCode = 1;
    private static final int authComRequestCode = 2;
    String authinfo = null;

    private boolean hasRequestComAuth = false;
    String TAG = "SplashActivity";

    @Override
    protected void onCreate(Bundle arg0) {
       //gxw- setStatusBar();
        super.onCreate(arg0);
        setContentView(R.layout.activity_splash);

        ivSplash = (ImageView) this.findViewById(R.id.iv_splash);
        AlphaAnimation animation = new AlphaAnimation(0.3f, 1.0f);
        animation.setDuration(1500);
        ivSplash.startAnimation(animation);

        mActivity = this;


        new Thread(new Runnable() {
            public void run() {
                Looper.prepare();

                    initNav();

                Looper.loop();
            }
        }).start();

    }


    /**
     * 初始化百度导航
     */
    private boolean initDirs() {
        mSDCardPath = Utils.getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }


    private boolean hasBasePhoneAuth() {
        // TODO Auto-generated method stub

        PackageManager pm = mActivity.getPackageManager();
        for (String auth : authBaseArr) {
            if (pm.checkPermission(auth, mActivity.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    /**
     * 内部TTS播报状态回传handler
     */
    private Handler ttsHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type = msg.what;
            switch (type) {
                case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
                    // showToastMsg("Handler : TTS play start");
                    break;
                }
                case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
                    // showToastMsg("Handler : TTS play end");
                    break;
                }
                default:
                    break;
            }
        }
    };
    private void initNavi() {

        BNOuterTTSPlayerCallback ttsCallback = null;

        // 申请权限
        if (android.os.Build.VERSION.SDK_INT >= 23) {

            if (!hasBasePhoneAuth()) {

                this.requestPermissions(authBaseArr, authBaseRequestCode);
                return;

            }
        }

        BaiduNaviManager.getInstance().init(mActivity, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {
            @Override
            public void onAuthResult(int status, String msg) {
                if (0 == status) {
                    authinfo = "key校验成功!";
                } else {
                    authinfo = "key校验失败, " + msg;
                }

                Log.i(TAG,authinfo);
		/*gxw-s		mActivity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Log.i(TAG,authinfo);
						Toast.makeText(mActivity, authinfo, Toast.LENGTH_LONG).show();
					}
				});gxw-e*/
            }

            public void initSuccess() {
                //gxw-Toast.makeText(mActivity, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
                Log.i(TAG,"百度导航引擎初始化成功");
                MyApplication.hasInitSuccess = true;
                initSetting();
            }

            public void initStart() {
                Log.i(TAG,"百度导航引擎初始化开始");
                //gxw-Toast.makeText(mActivity, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
            }

            public void initFailed() {
                Log.i(TAG,"百度导航引擎初始化失败");
                Toast.makeText(mActivity, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
            }

        }, null, ttsHandler, ttsPlayStateListener);

    }


    /**
     * 内部TTS播报状态回调接口
     */
    private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {

        @Override
        public void playEnd() {
            // showToastMsg("TTSPlayStateListener : TTS play end");
        }

        @Override
        public void playStart() {
            // showToastMsg("TTSPlayStateListener : TTS play start");
        }
    };

    private void initSetting() {
        // BNaviSettingManager.setDayNightMode(BNaviSettingManager.DayNightMode.DAY_NIGHT_MODE_DAY);
        BNaviSettingManager
                .setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // BNaviSettingManager.setPowerSaveMode(BNaviSettingManager.PowerSaveMode.DISABLE_MODE);
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);
        Bundle bundle = new Bundle();
        // 必须设置APPID，否则会静音
        bundle.putString(BNCommonSettingParam.TTS_APP_ID, "9810446");
        BNaviSettingManager.setNaviSdkParam(bundle);
    }

    @Override
    protected void onPostResume() {

        Log.i(TAG,"onPostResume");
        super.onPostResume();
    }


    @Override
    protected void onResume() {
        Log.i(TAG,"onResume");
        super.onResume();
    }

    private void initNav() {

        if (initDirs()) {
            initNavi();
        }
    }
    @Override
    protected void onStart() {
        super.onStart();

        new Thread(new Runnable() {
            public void run() {
                Looper.prepare();
                if (true) {   // 如果曾经登录过，直接


                    long start = System.currentTimeMillis();
                    //在这里预先读取点数据给 下一个页面的显示做准备
                   //GXW- initNav();
                    long costTime = System.currentTimeMillis() - start;
                    //wait
                    if (sleepTime - costTime > 0) {
                        try {
                            Thread.sleep(sleepTime - costTime);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    startActivity(new Intent(SplashActivity.this, LoginActivity.class));
                    finish();
                }/* else {
                    try {
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                    }
                    startActivity(new Intent(SplashActivity.this, LoginActivity.class));
                    finish();
                }*/
                Looper.loop();
            }
        }).start();

    }
}
